package com.example.service;

import com.example.client.PaymentClient;
import com.example.common.Result;
import com.example.entity.Order;
import com.example.entity.Payment;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class OrderService {
    private final Map<Long, Order> orderMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong();
    private final PaymentClient paymentClient;

    public OrderService(PaymentClient paymentClient) {
        this.paymentClient = paymentClient;
    }

    public Order create(Order order) {
        order.setId(idGenerator.incrementAndGet());
        order.setStatus(0); // 初始状态为未支付
        orderMap.put(order.getId(), order);
        return order;
    }

    public Order getOrderById(Long id) {
        return orderMap.get(id);
    }

    public Order pay(Long id) {
        Order order = orderMap.get(id);
        if (order != null && order.getStatus() == 0) {
            // 创建支付记录
            Payment payment = new Payment(null, "PAY" + order.getOrderNo(), order.getAmount());
            Result<?> result = paymentClient.create(payment);
            if (result.getCode() == 200) {
                order.setStatus(1);
                order.setPaymentId(((Payment)result.getData()).getId());
                orderMap.put(id, order);
            }
        }
        return order;
    }
} 